import 'package:flutter/material.dart';
import '../models/friend_model.dart';
import '../repositories/friend_repository.dart';
import '../errors/error_handler.dart';
import '../services/error_logger_service.dart';

class ContactsViewModel extends ChangeNotifier {
  final FriendRepository _friendRepository;

  ContactsViewModel(this._friendRepository);

  bool _isLoading = false;
  String? _errorMessage;
  List<FriendModel> _friends = [];

  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  List<FriendModel> get friends => _friends;
  bool get hasError => _errorMessage != null;

  /// 加载好友列表
  Future<void> loadFriends() async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await _friendRepository.getFriends();

      _isLoading = false;

      if (response.success && response.data != null) {
        _friends = response.data!;
        _errorMessage = null;
      } else {
        _errorMessage = response.message;
        _friends = [];
      }
      notifyListeners();
    } catch (e) {
      _isLoading = false;
      _errorMessage = ErrorHandler.getErrorMessage(e);
      _friends = [];
      ErrorLoggerService.logError(e, context: 'LoadFriends');
      notifyListeners();
    }
  }

  /// 刷新好友列表
  Future<void> refresh() async {
    await loadFriends();
  }

  /// 删除好友
  Future<bool> removeFriend(int friendId) async {
    try {
      final response = await _friendRepository.removeFriend(friendId);

      if (response.success) {
        _friends.removeWhere((friend) => friend.userId == friendId);
        notifyListeners();
        return true;
      } else {
        _errorMessage = response.message;
        notifyListeners();
        return false;
      }
    } catch (e) {
      _errorMessage = ErrorHandler.getErrorMessage(e);
      ErrorLoggerService.logError(e, context: 'RemoveFriend');
      notifyListeners();
      return false;
    }
  }

  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 清理所有数据（退出登录时调用）
  void clear() {
    _friends = [];
    _errorMessage = null;
    _isLoading = false;
    notifyListeners();
  }
}

